<template>
  <div class="settings">
    <van-nav-bar safe-area-inset-top placeholder :title="$t('Load1Setting')" left-arrow fixed @click-left="onClickLeft" />
    <div class="marginTop15">
      <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
        <van-cell-group>
          <van-cell :title="$t('Status')" :value="revealDatas.relay1Status==1?$t('Open'):$t('Off')" />
          <van-cell :title="$t('Power')" :value="revealDatas.relay1Power | numFilter(2,'W')" />
          <van-cell :title="$t('Energy')" :value="revealDatas.relay1Energy | numFilter(2,'kWh')" />
          <van-cell :title="$t('Match')">
            <template #right-icon>
              <van-button size="small" :type="types" round class="setbtn" @click="setMatch">{{$t('Save')}}</van-button>
            </template>
          </van-cell>
          <resetINVEnergyPTVue :setName="$t('ResetLoadEnergy')" :reg="106"></resetINVEnergyPTVue>
        </van-cell-group>
        <van-collapse v-model="activeNames">
          <van-collapse-item :title="$t('Load1Setting')" name="1" v-if="isMatch">
          <van-form @submit="Relay1SettingSubmit">
            <van-field :value="LocalArr.TriggerMode" :label="$t('TriggerMode')" readonly clickable name="picker" input-align="right" @click="showTrigger = true" />
            <van-popup v-model="showTrigger" round position="bottom">
              <van-picker show-toolbar :columns="triggerArr" 
                @cancel="showTrigger = false" 
                @confirm="triggerModeConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <van-field :value="LocalArr.ManualMode" :label="$t('ManualControl')" readonly clickable name="picker" input-align="right" @click="showManual = true" v-if="TriggerModeCode==1" />
            <van-popup v-model="showManual" round position="bottom">
              <van-picker show-toolbar :columns="manualArr" 
                @cancel="showManual = false" 
                @confirm="manualConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="LocalArr.TrigPowerValue" 
              :label="$t('TrigPower')" 
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixed1,message: `${$t('Range')}：50-5000` }]" 
            />
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="LocalArr.TrigTimeSetValue" 
              :label="$t('TriggerMinutes')" 
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixed2,message: `${$t('Range')}：1-10` }]" 
            />
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="LocalArr.CloseTimeSetValue" 
              :label="$t('CloseTimeSet')" 
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixedTwo1,message: `${$t('Range')}：0.1-24.0` }]" 
            />
            <van-cell :title="$t('StartTime')" :value="LocalArr.startTimeValue" @click="showStartTime=true" v-if="TriggerModeCode==4" />
            <van-popup v-model="showStartTime" round position="bottom">
              <van-datetime-picker v-model="currentStartTime" type="time" 
                @cancel="showStartTime = false" 
                @confirm="startTimeConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <van-cell :title="$t('EndTime')" :value="LocalArr.endTimeValue" @click="showEndTime=true" v-if="TriggerModeCode==4" />
            <van-popup v-model="showEndTime" round position="bottom">
              <van-datetime-picker v-model="currentEndTime" type="time" 
                @cancel="showEndTime = false" 
                @confirm="endTimeConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <div class="factorBtnBox">
              <van-button block round>{{$t('Save')}}</van-button>
            </div>
          </van-form>
        </van-collapse-item>
        </van-collapse>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import resetINVEnergyPTVue from '../../../components/ResetINVEnergy/ResetINVEnergyPT'
export default {
  components:{
    resetINVEnergyPTVue
  },
  data(){
    return {
      isLoading:false,
      activeNames:[],
      revealDatas:[],
      types:'primary',
      isMatch:false,
      MatchValue:'',
      showTrigger:false,
      triggerArr:[this.$t('Disabled'),this.$t('Manual'),this.$t('Once'),this.$t('Cycle'),this.$t('Force')],
      TriggerModeCode:'',
      showManual:false,
      manualArr:[this.$t('Off'),this.$t('Open')],
      ManualModeCode:'',
      showStartTime:false,
      currentStartTime:'',
      showEndTime:false,
      currentEndTime:'',
      LocalArr:{
        TriggerMode:'',
        ManualMode:'',
        TrigPowerValue:'',
        TrigTimeSetValue:'',
        CloseTimeSetValue:'',
        startTimeValue:'',
        endTimeValue:''
      }
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:'/rfcontrol'});
    },
    //获取展示数据
    async setRfRevealData(){
      let data = await this.SETAPI.setRfRevealData(localStorage.getItem('domain'),{'tokenId':localStorage.getItem('tokenId'),'sn':localStorage.getItem('sn'),'wifiSn':localStorage.getItem('wifiSN')});
      this.revealDatas=data.result||[];
      //判断匹配状态
      if(this.revealDatas.relay1answer==0){
        this.types='primary';
        this.isMatch=true;
      }else if(this.revealDatas.relay1answer==9||this.revealDatas.relay1answer==10){
        this.types='warning';
        this.isMatch=false;
      }else{
        this.types='danger';
        this.isMatch=false;
      }
    },
    triggerModeConfirm(value,i){
      this.showTrigger=false;
      this.LocalArr.TriggerMode=value;
      this.TriggerModeCode=i;
    },
    manualConfirm(value,i){
      this.showManual=false;
      this.LocalArr.ManualMode=value;
      this.ManualModeCode=i;
    },
    startTimeConfirm(val){
      this.showStartTime=false;
      this.LocalArr.startTimeValue=val;
    },
    endTimeConfirm(val){
      this.showEndTime=false;
      this.LocalArr.endTimeValue=val;
    },
    //设置Match
    async setMatch(){
      let params={
        'optType':'setReg',
        'sn':localStorage.getItem('wifiSN'),
        'tokenId':localStorage.getItem('tokenId'),
        'num':1,
        'Data':JSON.stringify([{'reg':97,'val':1}])
      };
      this.comm.loadingShow();
      let data = await this.SETAPI.setInvMachinePT(localStorage.getItem('domain'), params);
      if (data.success) {
        this.comm.toastSuccess();
        /*判断用户的选择*/
        this.isMatch=true;
        this.types='primary';
      }else {
        this.comm.toastFail();
      }
    },
    //Relay1参数设置
    Relay1SettingSubmit(){
      let StartTimeArr=this.LocalArr.startTimeValue.split(':');
      let EndTimeArr=this.LocalArr.endTimeValue.split(':');
      let formData=[
        {'reg':105,'val':this.ManualModeCode},
        {'reg':100,'val':this.TriggerModeCode},
        {'reg':98,'val':this.LocalArr.TrigPowerValue},
        {'reg':99,'val':(this.LocalArr.CloseTimeSetValue)*256+Number(this.LocalArr.TrigTimeSetValue)},
        {'reg':101,'val':parseInt(StartTimeArr[1])*256+parseInt(StartTimeArr[0])},
        {'reg':102,'val':parseInt(EndTimeArr[1])*256+parseInt(EndTimeArr[0])}
      ];
      this.comm.setDataPT(6,formData);
    },
    fixed1(val){
      let vaild;
      if(val>=50&&val<=5000){
        vaild=true;
      }else{
        vaild=false;
      }
      return vaild;
    },
    fixed2(val){
      let vaild;
      if(val>=1&&val<=10){
        vaild=true;
      }else{
        vaild=false;
      }
      return vaild;
    },
    fixedTwo1(val){
      return this.comm.fixedTwo(val,0.1,24);
    },
    //获取设置数据
    async getData(){
      this.comm.loadingShow();
      let datas = await this.SETAPI.setGetDataPT(localStorage.getItem('domain'),{'tokenId':localStorage.getItem('tokenId'),'sn':localStorage.getItem('wifiSN')});
      if(datas.result!=null&&datas.result!="tokenId不合法!"){
        let dataArr=datas.result;
        this.TriggerModeCode=dataArr[107];
        this.LocalArr.TriggerMode=this.triggerArr[this.TriggerModeCode];
        this.ManualModeCode=dataArr[110];
        this.LocalArr.ManualMode=this.manualArr[this.ManualModeCode];
        this.LocalArr.TrigPowerValue=dataArr[105];

        let TrigTimeSetHandle= dataArr[106];
        let TrigTimeSetHandle1=parseInt(TrigTimeSetHandle/256);
        let TrigTimeSetHandle2=TrigTimeSetHandle%256;
        this.LocalArr.TrigTimeSetValue=TrigTimeSetHandle2;
        this.LocalArr.CloseTimeSetValue=TrigTimeSetHandle1/10;

        let startTime1Handle= dataArr[108];
        let startTime1Handle1= parseInt(startTime1Handle/256);
        let startTime1Handle2=startTime1Handle%256;
        startTime1Handle1=parseInt(startTime1Handle1)>=10?startTime1Handle1:"0"+startTime1Handle1;
        startTime1Handle2=parseInt(startTime1Handle2)>=10?startTime1Handle2:"0"+startTime1Handle2;
        this.LocalArr.startTimeValue=`${startTime1Handle1}:${startTime1Handle2}`;

        let endTime1Handle= dataArr[109];
        let endTime1Handle1= parseInt(endTime1Handle/256);
        let endTime1Handle2=endTime1Handle%256;
        endTime1Handle1=parseInt(endTime1Handle1)>=10?endTime1Handle1:"0"+endTime1Handle1;
        endTime1Handle2=parseInt(endTime1Handle2)>=10?endTime1Handle2:"0"+endTime1Handle2;
        this.LocalArr.endTimeValue=`${endTime1Handle1}:${endTime1Handle2}`;
      }else{
        this.comm.tipsShow('InvNoResponse');
      }
    },
    onRefresh(){
      this.isLoading = false;
      for(let i in this.LocalArr){
        this.LocalArr[i]='';
      }
      this.setRfRevealData();
      this.getData();
    }
  },
  mounted(){
    this.setRfRevealData();
    this.getData();
  }
}
</script>

<style scoped lang="less">

</style>
